package com.demo.las.service;

import com.demo.las.entity.PersonalAffair;
import com.demo.las.dto.PersonalAffairDTO;
import com.demo.las.repository.PersonalAffairRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PersonalAffairService {

    @Autowired
    private PersonalAffairRepository personalAffairRepository;

    @Autowired
    private UserService userService;

    public List<PersonalAffairDTO> getAffairsByUser(Long userId) {
        return personalAffairRepository.findAffairsViewByUserId(userId);
    }

    public PersonalAffair createAffair(PersonalAffair affair) {
        // 基础校验
        if (affair.getUserId() == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        if (userService.getUserById(affair.getUserId()).isEmpty()) {
            throw new IllegalArgumentException("用户不存在，请检查登录状态或用户ID");
        }

        // 业务校验
        if (!affair.isDateRangeValid()) {
            throw new IllegalArgumentException("结束时间不能早于开始时间");
        }
        if (affair.getCompletionRating() == null || affair.getCompletionRating() < 1 || affair.getCompletionRating() > 5) {
            throw new IllegalArgumentException("完成度评级必须在1到5之间");
        }
        if (personalAffairRepository.existsByAffairCode(affair.getAffairCode())) {
            throw new IllegalArgumentException("事务编号已存在");
        }
        return personalAffairRepository.save(affair);
    }

    // 新增：删除个人事务
    public void deleteAffair(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("事务ID不能为空");
        }
        if (!personalAffairRepository.existsById(id)) {
            throw new IllegalArgumentException("个人事务不存在");
        }
        personalAffairRepository.deleteById(id);
    }
}